import axios from "axios"
import config  from "./config.base"

let instance = axios.create({
    headers: {'content-type': 'application/json'}
})

instance.defaults.baseURL = config.baseURL
// instance.defaults.withCredentials = true

// 添加请求拦截器
instance.interceptors.request.use(function (config) {
    config.headers.Authorization = window.sessionStorage.getItem("token");
    // console.log(config)
    return config
}, function (error) {
    return Promise.reject(error)
})

// 添加响应拦截器
instance.interceptors.response.use(function (response) {
    if (response.status == 200) {
        if (response.data && response.data.meta) {
            const code = response.data.meta.status;//真正项目中的接口成功后的请求响应码code
            if(code == 200 || code == 201){
                return response.data.data
            } else {
                return Promise.reject(response.data.meta)
            }
            // const loginUrl = Cookies.get("sysUrl")
            // Cookies.remove("userName", { domain: "abc.com" })
            // Cookies.remove("token", { domain: "abc.com" })
            // localStorage.clear()
            // window.location.href = loginUrl
        }    
    } 
    return Promise.reject({msg:'数据异常'})
}, function (error) {
    if(error && error.response && error.response.status == '401') {
        console.log('--- 401 error response ---')
        // const loginUrl = Cookies.get("sysUrl")
        // Cookies.remove("userName", { domain: "abc.com" })
        // Cookies.remove("token", { domain: "abc.com" })
        // localStorage.clear()
        // window.location.href = loginUrl
    }     
    return Promise.reject(error)
})

export default instance
